/*
 * Copyright kecp
 * Apr 24, 2010
 */

package Tool;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;


/**
 * 调试器，用于控制调试信息的输出
 * @author kecp
 */
public class Debugger {

    static private Debugger theDebugger = new Debugger();

    private Debugger() {
    }

    /**
     * 清楚所有日志记录
     */
    static public void cleanLog() {
        RecordStore rms;
        try {
            rms = RecordStore.openRecordStore("debugLog", true, RecordStore.AUTHMODE_ANY, true);
             RecordEnumeration re = rms.enumerateRecords(null, null, true);
             
            while (re.hasNextElement()) {
                 int id=re.nextRecordId();
                 rms.deleteRecord(id);
            }
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
    }


    static public void addDebugInfo(Exception ex,String info ){
        System.out.println(info);
        System.out.println(ex.toString());
        info += '\n';
        try {
            RecordStore rms = RecordStore.openRecordStore("debugLog", true, RecordStore.AUTHMODE_ANY, true);
            byte []bs = Toolkit.stringToUtfBytes(info);
            rms.addRecord( bs , 0, bs.length);
            bs = Toolkit.stringToUtfBytes(ex.toString());
            rms.addRecord( bs , 0, bs.length);
            rms.closeRecordStore();
        } catch (RecordStoreException exc) {
            exc.printStackTrace();
        }
    }
    static public void printDebugInfo(String info) {
        System.out.println(info);
    }
    static public void addDebugInfo(String info ){

        System.out.println(info);
        info += '\n';
        try {
            RecordStore rms = RecordStore.openRecordStore("debugLog", true, RecordStore.AUTHMODE_ANY, true);
            byte []bs = Toolkit.stringToUtfBytes(info);
            rms.addRecord( bs , 0, bs.length);
            rms.closeRecordStore();
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
        
    }

    /**
     *
     * @return 所有日志内容
     */
    static public String getLog() {
        StringBuffer sb = new StringBuffer();
        try {
      
            RecordStore rms  = RecordStore.openRecordStore("debugLog", false);
            RecordEnumeration re = rms.enumerateRecords(null, null, true);
            while (re.hasNextElement()) {
                 int id=re.nextRecordId();
                 byte b[] = rms.getRecord(id);
                 if( b != null )
                    sb.append(Toolkit.utfBytesToString(b));
            }
            rms.closeRecordStore();
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
            return "";
        }
        return sb.toString();
    }
}
